package ch.headshot.photomap.client.editor.control;

import ch.headshot.photomap.client.editor.view.Map;
import ch.headshot.photomap.client.gpx.Track;
import ch.headshot.photomap.client.gpx.TrackSegment;
import ch.headshot.photomap.client.gpx.WayPoint;

import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.Window;

public class CenterMapCommand implements Command {

	private final Track track;

	public CenterMapCommand(Track track) {
		this.track = track;
	}

	public void execute() {
		Double latmin = null;
		Double latmax = null;
		Double lonmin = null;
		Double lonmax = null;
		for (TrackSegment seg : track.getSegments()) {
			for (WayPoint point : seg.getPoints()) {
				Double lat = point.getLatitude();
				if (latmin == null || lat < latmin) {
					latmin = lat;
				}
				if (latmax == null || lat > latmax) {
					latmax = lat;
				}

				Double lon = point.getLongitude();
				if (lonmin == null || lon < lonmin) {
					lonmin = lon;
				}
				if (lonmax == null || lon > lonmax) {
					lonmax = lon;
				}
			}
		}

		if (latmin == null || lonmax == null || latmin == null || latmax == null) {
			Window.alert("Track contains no points to center on");
			return;
		}

		Map.getInstance().center(latmax, lonmax, latmin, lonmin);
	}

}
